<?php

namespace Gaolei\YiiRBAC\models\user;

use Yii;
use yii\web\User;
use yii\helpers\Url;
use yii\web\Response;
use yii\web\ForbiddenHttpException;

class Admin extends User
{

    public $loginUrl = ['/admin/adminer/login'];

    /**
     * @param bool $checkAjax
     * @param bool $checkAcceptHeader
     * @return Response
     * @throws ForbiddenHttpException
     */
    public function loginRequired($checkAjax = true, $checkAcceptHeader = true): Response
    {
        $request = Yii::$app->getRequest();
        $canRedirect = !$checkAcceptHeader || $this->checkRedirectAcceptable();
        if (
            $this->enableSession && $request->getIsGet() &&
            (!$checkAjax || !$request->getIsAjax()) && $canRedirect
        ) {
            $this->setReturnUrl($request->getAbsoluteUrl());
        }
        if ($this->loginUrl !== null) {
            $loginUrl = (array)$this->loginUrl;
            $response = Yii::$app->response;
            if ($canRedirect) {
                if ($loginUrl[0] !== Yii::$app->requestedRoute) {
                    return $response->redirect($this->loginUrl);
                }
            } else {
                $response->setStatusCode(302);
                return Yii::$app->controller->asJson([
                    'code' => 302, 'msg' => '当前未登录或登录状态已失效', 'data' => Url::to($loginUrl)
                ]);
            }
        }
        throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
    }

    /**
     * @param string $permissionName
     * @param array $params
     * @param bool $allowCaching
     * @return bool|mixed
     * @author gaolei 2021/10/7 6:57 下午
     */
    public function can($permissionName, $params = [], $allowCaching = true)
    {
        return parent::can($permissionName, $params, $allowCaching);
    }

}